package com.xiaolanshu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaolanshu.entity.Goods;
import com.xiaolanshu.exception.BusinessException;
import com.xiaolanshu.service.GoodsService;
import com.xiaolanshu.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/backend")
public class BackendController {

    @Autowired
    private GoodsService goodsService;

    /**
     * 后台商品分页列表
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping
    public ResponseEntity backend(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int pageSize){
        //分页查询商品
        Page<Goods> goodsPage = goodsService.pageGoods(page,pageSize);

        return ResponseEntity.ok(goodsPage);
    }

    /**
     * 商品更新
     * @param param
     * @param goodsId
     * @return
     */
    @PutMapping("/update/{goodsId}")
    public ResponseEntity update(@RequestBody Map param,@PathVariable Long goodsId){

        int update = goodsService.update(param, goodsId);
        if(!String.valueOf(update).equals("")){
            return ResponseEntity.status(200).body("更新成功");
        }
        else {
            //更新失败抛出自定义业务异常
            throw new BusinessException(ErrorResult.crudError());

        }
    }

    @PutMapping("/delete/{goodsId}")
    public ResponseEntity delete(@PathVariable Long goodsId){

        int delete = goodsService.delete(goodsId);
        //判断delete不为空
        if (!String.valueOf(delete).equals("")){
            return ResponseEntity.status(200).body("删除成功");
        }
        else {
            //更新失败抛出自定义业务异常
            throw new BusinessException(ErrorResult.crudError());
        }
    }

}
